package com.tikou.permission;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.tikou.androidadvanceproject.R;

/**
 * Created by Tikou on 2017/11/10.
 * 作者：TianNuo
 * 邮箱：1320917731@qq.com
 * 说明：6.0权限获取学习
 * 参考：
 */

public class PermissionActivity extends AppCompatActivity implements View.OnClickListener{
    private static final int CALL_PHONE_REQUEST_CODE = 0X0011;
    private Button btn_call;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_permission);
        btn_call = findViewById(R.id.btn_call);
        btn_call.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        int viewId = v.getId();
        if (viewId == R.id.btn_call){
            testCall();
        }
    }

    private void testCall() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CALL_PHONE) !=
                PackageManager.PERMISSION_GRANTED
                ){
            Toast.makeText(this,"申请权限",Toast.LENGTH_SHORT).show();
            ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.CALL_PHONE},CALL_PHONE_REQUEST_CODE);
        }else {
            callPhone();
        }
    }

    @SuppressLint("MissingPermission")
    private void callPhone() {
        Intent intent = new Intent(Intent.ACTION_CALL);
        Uri data = Uri.parse("tel:13865563861");
        intent.setData(data);
        startActivity(intent);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == CALL_PHONE_REQUEST_CODE){
            if (grantResults.length!=0&&grantResults[0] == PackageManager.PERMISSION_GRANTED){
                callPhone();
            }else {
                Toast.makeText(this,"权限呢被拒绝",Toast.LENGTH_SHORT).show();
            }
        }
    }
}
